package cn.tedu.overhaul.management.service.impl;

import cn.tedu.overhaul.management.config.IsDateInFormat;
import cn.tedu.overhaul.management.dto.persist.mapper.OverhaulMapper;
import cn.tedu.overhaul.management.dto.persist.mapper.OverhaulRentMapper;
import cn.tedu.overhaul.management.dto.persist.repository.IOverhaulRentRepository;
import cn.tedu.overhaul.management.dto.persist.repository.IOverhaulRepository;
import cn.tedu.overhaul.management.pojo.dto.*;
import cn.tedu.overhaul.management.pojo.entity.Overhaul;
import cn.tedu.overhaul.management.pojo.entity.OverhaulRent;
import cn.tedu.overhaul.management.pojo.vo.*;
import cn.tedu.overhaul.management.service.IOverhaulRentService;
import cn.tedu.overhaul.management.service.IOverhaulService;
import cn.tedu.rtms.commons.ex.ServiceException;
import cn.tedu.rtms.commons.pojo.vo.PageData;
import cn.tedu.rtms.commons.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class OverhaulRentServiceImpl implements IOverhaulRentService {
    @Value("${overhaul.crud.default-query-page-size}")
    private Integer defaultQueryPageSize;
    @Autowired
    OverhaulMapper overhaulMapper;

    @Autowired
    IOverhaulRentRepository iOverhaulRentRepository;

    @Autowired
    OverhaulRentMapper overhaulRentMapper;

    @Override
    public String addNew(OverhaulRentAddNewDTO overhaulRentAddNewDTO) {

        log.debug("开始处理[添加借用信息],参数:{}",overhaulRentAddNewDTO);
        // 创建OverhaulRent对象
        OverhaulRent overhaulRent=new OverhaulRent();
        Long userId=iOverhaulRentRepository.selectByName(overhaulRentAddNewDTO.getName());
        if(userId==null){
            log.debug("您输入的名字{}不是用户",overhaulRentAddNewDTO.getName());
            String message ="添加借用失败，输入的名字不是用户！";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        overhaulRent.setUserId(userId);


        //根据联机选择器返回的id值查询出工具编号
        long toolNumberId=Long.parseLong(overhaulRentAddNewDTO.getTool().get(1));
        String toolNumber=overhaulMapper.selectToolNumber(toolNumberId);

        Long toolId2=overhaulRentMapper.selectByToolNumber(toolNumber);
        overhaulRent.setToolId(toolId2);


        overhaulRent.setStart(LocalDateTime.now());
        int status= overhaulRentMapper.selectStatus(toolNumber);
        if(status==2){
            String message ="借用工具失败，借用的工具正在使用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }


        iOverhaulRentRepository.insert(overhaulRent);



        int updateStatus=overhaulMapper.updateStatus(2,toolNumberId);
        if(updateStatus==0){
            String message ="更改检修设备表状态失败，此id的工具不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        log.debug("开始处理[更改检修设备表状态]完成");
        return "200";
    }

    @Override
    public PageData<RentVO> selectRent(Integer pageNum) {
        log.debug("开始处理【借用记录表】的业务，页码：{}", pageNum);
        PageData<RentVO> pageData=iOverhaulRentRepository.selectRent(pageNum,defaultQueryPageSize);
        return pageData;
    }

    @Override
    public PageData<RentVO> selectRent(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【借用记录表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageData<RentVO> pageData = iOverhaulRentRepository.selectRent(pageNum, pageSize);
        return pageData;
    }

    @Override
    public int updateEndTime(Long id,String toolNumber) {
        log.debug("开始处理【归还工具】的业务，参数id：{}", id);
        Long toolId2=overhaulRentMapper.selectByToolNumber(toolNumber);
        int updateStatus=overhaulMapper.updateStatus(1,toolId2);
        if(updateStatus==0){
            String message ="更改检修设备表状态失败，此id的工具不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        log.debug("开始处理[更改检修设备表状态]完成");
        return iOverhaulRentRepository.updateEndTime(id);
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【根据ID删除借用记录】的业务，参数：{}", id);
        // 调用Mapper对象的getStandardById()执行查询
        RentOriginalVO queryResult=iOverhaulRentRepository.getStandardById(id);
        // 判断查询结果是否为null
        if (queryResult == null) {
            String message = "删除借用记录失败，尝试删除的借用记录数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        // 调用Mapper对象的deleteById()方法执行删除
        log.debug("即将执行删除，参数：{}", id);
        iOverhaulRentRepository.deleteById(id);
    }




    @Override
    public RentVO getStandardByIdAll(Long id) {
        log.debug("开始处理【根据ID修改面板查询借用记录】的业务，参数：{}", id);
        // 调用Mapper对象的getStandardById()执行查询
        RentOriginalVO queryResult=iOverhaulRentRepository.getStandardById(id);
        if(queryResult==null){
            String message ="根据ID修改面板查询借用记录失败，此id的记录不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        RentVO rentVO=new RentVO();
        rentVO.setId(queryResult.getId());
        String name=overhaulRentMapper.selectById(queryResult.getUserId());
        rentVO.setName(name);
        List<ToolNameNumberVO> list=overhaulRentMapper.selectByToolId(queryResult.getToolId());
        for (ToolNameNumberVO toolNameNumberVO : list) {
            rentVO.setToolName(toolNameNumberVO.getName());
            rentVO.setToolNumber(toolNameNumberVO.getNumber());
        }
        rentVO.setStart(queryResult.getStart());
        rentVO.setEnd(queryResult.getEnd());
        if(queryResult.getModificationTime()==null){
            rentVO.setModificationTime("未修改");
        }else{
            rentVO.setModificationTime(queryResult.getModificationTime());
        }
        if(queryResult.getModificationFrequency()==null){
            rentVO.setModificationFrequency(0);
        }else{
            rentVO.setModificationFrequency(queryResult.getModificationFrequency());
        }

        return rentVO;
    }


    @Override
    public int updateInfoById(Long id, OverhaulRentUpdateDTO overhaulRentUpdateDTO) {
        log.debug("开始处理【修改借用记录】的业务，参数：{},{}", id,overhaulRentUpdateDTO);
        RentOriginalVO queryResult= iOverhaulRentRepository.getStandardById(id);
        if(queryResult==null){
            //是:抛出异常
            String message ="根据ID修改修改借用记录失败，根据ID修改的借用记录不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }


        // 创建OverhaulRentUpdateAllDTO对象
        OverhaulRentUpdateAllDTO overhaulRentUpdateAllDTO=new OverhaulRentUpdateAllDTO();
        overhaulRentUpdateAllDTO.setId(id);
        Long userId=overhaulRentMapper.selectByName(overhaulRentUpdateDTO.getName());
        overhaulRentUpdateAllDTO.setUserId(userId);
        Long toolId=overhaulRentMapper.selectByToolNumber(overhaulRentUpdateDTO.getToolNumber());
        overhaulRentUpdateAllDTO.setToolId(toolId);

        //格式化数据
        String str1 = overhaulRentUpdateDTO.getStart();
        String str2 = overhaulRentUpdateDTO.getEnd();
        String targetFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
        boolean isValidFormat = IsDateInFormat.isDateInFormat(str1,targetFormat);
        boolean isValidFormat2 = IsDateInFormat.isDateInFormat(str2,targetFormat);
        if(isValidFormat||isValidFormat2){
            // 解析原始日期字符串
            SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            Date date;
            Date date2;
            try {
                date = originalFormat.parse(str1);
                date2 = originalFormat.parse(str2);

                // 格式化日期为目标格式
                SimpleDateFormat targetFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String targetDate = targetFormat2.format(date);
                String targetDate2 = targetFormat2.format(date2);
                log.debug("原始日期: {},{}" , str1,str2);
                log.debug("目标日期: {},{}" , targetDate,targetDate2);
                str1=targetDate;
                str2=targetDate2;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        overhaulRentUpdateAllDTO.setStart(str1);
        overhaulRentUpdateAllDTO.setEnd(str2);
        overhaulRentUpdateAllDTO.setModificationTime(LocalDateTime.now());
        RentOriginalVO selectFrequency=overhaulRentMapper.getStandardById(overhaulRentUpdateAllDTO.getId());
        if(selectFrequency==null){
            //是:抛出异常
            String message ="根据ID修改借用记录失败，根据ID修改的借用记录不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        int frequency=0 ;
        if (selectFrequency.getModificationFrequency()!=null){
            frequency=selectFrequency.getModificationFrequency();
        }
        frequency++;
        log.debug("参数frequency:{}",frequency);
        overhaulRentUpdateAllDTO.setModificationFrequency(frequency);
        return iOverhaulRentRepository.update(overhaulRentUpdateAllDTO);
    }
}
